package top.bulk.logdynamic.controller;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;
import org.springframework.boot.logging.LogLevel;
import org.springframework.boot.logging.LoggingSystem;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 散装java
 * @date 2024-07-29
 */
@RestController
public class LogDynamicTestController {

    @Resource
    private LoggingSystem loggingSystem;

    @GetMapping("/test")
    public void test() {
        System.out.println("test");
    }

    /**
     * 通过 LoggerContext 来修改
     */
    @PostMapping("/changeLogLevel/{loggerName}/{level}")
    public static void changeLogLevel(@PathVariable("loggerName") String loggerName, @PathVariable("level") String level) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        Logger logger = loggerContext.getLogger(loggerName);
        logger.setLevel(Level.toLevel(level));
    }

    /**
     * 通过 spring 的 LoggingSystem 修改
     */
    @PostMapping("/springLoglevel")
    public void springLoglevel(@RequestParam String loggerName, @RequestParam String level) {
        loggingSystem.setLogLevel(loggerName, LogLevel.valueOf(level.toUpperCase()));
    }
}
